import { defineStore } from "pinia";

import { getUserMenus } from "@/api/auth.js";

export const useMenuStore = defineStore("menu", {
    persist: false,
    state: () => ({
        menuList: []
    }),
    actions: {
        getMenus() {
            return new Promise((resolve, reject) => {
                getUserMenus().then(res => {
                    if (res.code == 200) {
                        this.menuList = res.result
                        const routerData = JSON.parse(JSON.stringify(res.result)) // 用于最后添加到 Router 中的数据
                        const rewriteRoutes = filterAsyncRouter(routerData)

                        resolve(rewriteRoutes)
                    } else {
                        // API返回错误码时，清空菜单列表并reject
                        this.menuList = []
                        reject(new Error(res.message || '获取菜单失败'))
                    }
                }).catch(error => {
                    // 网络错误或其他异常时，清空菜单列表并reject
                    this.menuList = []
                    reject(error)
                })
            })
        }
    },
});

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
    return asyncRouterMap.filter(route => {
        route.component = loadView(route.component)
        if (route.children) {
            filterAsyncRouter(route.children)
        }

        return true
    })
}

const loadView = (view) => { // 路由懒加载
    let modules = import.meta.glob('../views/**/*.vue')
    return modules[`../views/${view}.vue`]
}